<template>
  <el-config-provider :locale="zhCn">
    <div class="sop-bulk-sending">
      <!-- 筛选条件区域 -->
      <filter-form
        v-model="filterForm"
        :form-items="formItems"
        @search="handleSearch"
        @reset="resetFilter"
        @update:modelValue="handleFilterChange"
        labelWidth="100px"
      />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="primary" @click="handleCreateTask">新增计划</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="taskList" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="sopTaskName" label="计划名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="marketingPlanStart" label="营销开始时间" min-width="160" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.marketingPlanStart ? scope.row.marketingPlanStart.slice(0, 10) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="marketingPlanEnd" label="营销结束时间" min-width="160" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.marketingPlanEnd ? scope.row.marketingPlanEnd.slice(0, 10) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="actualDays" label="营销天数" width="100" align="center">
            <template #default="scope">
              <span>{{ scope.row.actualDays || 0 }} 天</span>
            </template>
          </el-table-column>
          <el-table-column prop="taskNumber" label="任务数量" width="100" align="center">
            <template #default="scope">
              <span>{{ scope.row.taskNumber || 0 }}个</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="计划状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.type === 2 ? 'success' : scope.row.type === 1 ? 'info' : 'warning'">
                {{ scope.row.type === 2 ? '已完成' : scope.row.type === 1 ? '执行中' : '未开始' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createBy" label="创建人" min-width="120" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="250" fixed="right" align="center">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="success" link @click="handleViewDetail(scope.row)">任务</el-button>
              <el-button type="info" link @click="showTimeline(scope.row)">进度</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 计划对话框 -->
      <el-dialog v-model="taskDialogVisible" :title="dialogType === 'create' ? '新增计划' : '编辑计划'" width="500px" destroy-on-close class="task-dialog">
        <el-form :model="taskForm" label-width="110px" class="task-form" :rules="taskRules" ref="taskFormRef">
          <el-form-item label="计划名称" prop="taskName" required>
            <el-input v-model="taskForm.taskName" placeholder="请输入计划名称" />
          </el-form-item>
          <el-form-item label="营销时间" prop="timeRange" required>
            <el-date-picker
              v-model="taskForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="taskDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitTask">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="计划详情" width="90%" destroy-on-close class="detail-dialog">
        <SOPBulkSendingDetail
          v-if="detailDialogVisible"
          :sop-id="currentTaskId"
          :marketing-plan-end="currentTaskInfo?.marketingPlanEnd || ''"
          @close="detailDialogVisible = false"
        />
      </el-dialog>

      <!-- 进度弹窗 -->
      <TimelineDialog v-model:visible="timelineDialogVisible" :plan-stats="planStats" :timeline-data="timelineData" />
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import type { FormInstance, FormRules } from 'element-plus';
import * as SOPbulkSendingApi from '@/api/userRate/SOPbulkSending';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import TimelineDialog from '@/components/common/TimelineDialog.vue';

const { getSopMessageTaskList, addSopMessageTask, deleteSopMessageTask, updateSopMessageTask, getSopPrecisionProgress } = SOPbulkSendingApi;

// 动态导入 SOPBulkSendingDetail 组件
const SOPBulkSendingDetail = defineAsyncComponent(() => import('./SOPBulkSendingDetail.vue'));

type SopMessageTaskItem = {
  sopId: number;
  sopTaskName: string | null;
  marketingPlan: string | null;
  createBy: string | null;
  createTime: string;
  marketingPlanStart: string | null;
  marketingPlanEnd: string | null;
  taskNumber: number;
  actualDays: number | null;
  createByStr: string | null;
  type: number;
};

type ApiResponse<T> = {
  code: number;
  msg: string;
  data: T;
};

type PageResult<T> = {
  records: T[];
  total: number;
  size: number;
  current: number;
  orders: any[];
  optimizeCountSql: boolean;
  searchCount: boolean;
  maxLimit: number | null;
  countId: string | null;
  pages: number;
};

// 筛选表单
const filterForm = reactive({
  taskName: '',
  marketingPlanStart: '',
  marketingPlanEnd: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 计划列表数据
const taskList = ref<SopMessageTaskItem[]>([]);

// 计划对话框相关
const taskDialogVisible = ref(false);
const taskFormRef = ref<FormInstance>();
const dialogType = ref<'create' | 'edit'>('create');
const taskForm = reactive({
  sopId: 0,
  taskName: '',
  timeRange: [] as string[]
});

// 计划表单验证规则
const taskRules: FormRules = {
  taskName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  timeRange: [{ required: true, message: '请选择营销时间', trigger: 'change' }]
};

// 详情对话框相关
const detailDialogVisible = ref(false);
const currentTaskId = ref('');
const currentTaskInfo = ref<SopMessageTaskItem | null>(null);

// 表单项配置
const formItems = computed(() => [
  {
    type: 'input' as const,
    label: '计划名称',
    prop: 'taskName',
    placeholder: '请输入计划名称',
    clearable: true
  },
  {
    type: 'date' as const,
    label: '营销开始时间',
    prop: 'marketingPlanStart',
    placeholder: '请选择营销开始时间',
    valueFormat: 'YYYY-MM-DD',
    dateType: 'date',
    clearable: true
  },
  {
    type: 'date' as const,
    label: '营销结束时间',
    prop: 'marketingPlanEnd',
    placeholder: '请选择营销结束时间',
    valueFormat: 'YYYY-MM-DD',
    dateType: 'date',
    clearable: true
  }
]);

// 查询方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  try {
    // 获取本地存储的account和createBy
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const msgprofile = JSON.parse(localStorage.getItem('msgprofile') || '{}');
    const account = userInfo.username || '';
    const createBy = msgprofile.wx_id || '';

    // 使用传入的表单数据或当前的表单数据
    const searchData = formData || filterForm;
    const params: any = {
      taskName: searchData.taskName?.trim() || undefined,
      marketingPlanStart: searchData.marketingPlanStart?.trim() || undefined,
      marketingPlanEnd: searchData.marketingPlanEnd?.trim() || undefined,
      current: currentPage.value,
      size: pageSize.value,
      account,
      createBy
    };

    // 移除所有 undefined 的参数
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        delete params[key];
      }
    });

    const res = await getSopMessageTaskList(params);
    const response = res as unknown as ApiResponse<PageResult<SopMessageTaskItem>>;
    if (response.code === 200) {
      taskList.value = response.data.records;
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || '获取计划列表失败');
    }
  } catch (error) {
    console.error('获取计划列表失败:', error);
    ElMessage.error('获取计划列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilter = () => {
  // 重置筛选条件
  Object.keys(filterForm).forEach((key) => {
    (filterForm as any)[key] = '';
  });
  // 重置分页参数
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 新增计划
const handleCreateTask = () => {
  dialogType.value = 'create';
  taskForm.sopId = 0;
  taskForm.taskName = '';
  taskForm.timeRange = [];
  taskDialogVisible.value = true;
};

// 编辑计划
const handleEdit = (row: SopMessageTaskItem) => {
  dialogType.value = 'edit';
  taskForm.sopId = row.sopId;
  taskForm.taskName = row.sopTaskName || '';
  taskForm.timeRange = [row.marketingPlanStart || '', row.marketingPlanEnd || ''];
  taskDialogVisible.value = true;
};

// 提交计划
const submitTask = async () => {
  if (!taskFormRef.value) return;

  await taskFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const [marketingPlanStart, marketingPlanEnd] = taskForm.timeRange;
        const params = {
          taskName: taskForm.taskName,
          marketingPlanStart,
          marketingPlanEnd,
          createBy: JSON.parse(localStorage.getItem('userInfo') || '{}').username || '未知用户'
        };

        let res;
        if (dialogType.value === 'create') {
          res = await addSopMessageTask(params);
        } else {
          res = await updateSopMessageTask({
            ...params,
            sopId: taskForm.sopId.toString()
          });
        }

        const response = res as unknown as ApiResponse<null>;
        if (response.code === 200) {
          taskDialogVisible.value = false;
          ElMessage.success(dialogType.value === 'create' ? '新增计划成功' : '编辑计划成功');
          handleSearch();
        } else {
          ElMessage.error(response.msg || (dialogType.value === 'create' ? '新增计划失败' : '编辑计划失败'));
        }
      } catch (error) {
        console.error(dialogType.value === 'create' ? '新增计划失败:' : '编辑计划失败:', error);
        ElMessage.error(dialogType.value === 'create' ? '新增计划失败' : '编辑计划失败');
      }
    }
  });
};

// 删除计划
const handleDelete = (row: SopMessageTaskItem) => {
  ElMessageBox.confirm('确认删除该计划吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteSopMessageTask({ sopId: row.sopId.toString() });
        const response = res as unknown as ApiResponse<null>;
        if (response.code === 200) {
          ElMessage.success('删除成功');
          handleSearch();
        } else {
          ElMessage.error(response.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除计划失败:', error);
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {});
};

// 查看详情方法
const handleViewDetail = (row: SopMessageTaskItem) => {
  currentTaskId.value = row.sopId.toString();
  currentTaskInfo.value = row;
  detailDialogVisible.value = true;
};

// 处理分页变化
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.taskName = val.taskName || '';
  filterForm.marketingPlanStart = val.marketingPlanStart || '';
  filterForm.marketingPlanEnd = val.marketingPlanEnd || '';
};

// 进度相关
const timelineDialogVisible = ref(false);
type TimelineItem = {
  time: string;
  content: string;
  type: string;
  icon?: string;
  color?: string;
  user?: string;
  remark?: string;
  statusClass?: string;
};
const timelineData = ref<Array<TimelineItem>>([]);
const planStats = ref({
  totalDays: 10,
  executedDays: 6,
  totalTasks: 20,
  executedTasks: 12
});

function showTimeline(row: SopMessageTaskItem) {
  const msgprofile = JSON.parse(localStorage.getItem('msgprofile') || '{}');
  const wxId = msgprofile.wx_id || '';
  getSopPrecisionProgress({ wxId, sopId: row.sopId.toString() })
    .then((res: any) => {
      if (res && res.code === 200 && res.data) {
        planStats.value = {
          totalDays: res.data.actualDays || 0,
          executedDays: res.data.executedDays || 0,
          totalTasks: res.data.taskNumber || 0,
          executedTasks: res.data.executedNumber || 0
        };
        timelineData.value = (res.data.umWechatMessageTask || []).map((task: any) => {
          let statusText = '';
          let type = '';
          let color = '';
          let statusClass = '';
          if (task.status === '2') {
            statusText = '已完成';
            type = 'success';
            color = '#67C23A';
            statusClass = 'remark-success';
          } else if (task.status === '3') {
            statusText = '失败';
            type = 'danger';
            color = '#F56C6C';
            statusClass = 'remark-danger';
          } else if (task.status === '0') {
            statusText = '待发送';
            type = 'warning';
            color = '#E6A23C';
            statusClass = 'remark-warning';
          } else if (task.status === '1') {
            statusText = '进行中';
            type = 'info';
            color = '#409EFF';
            statusClass = 'remark-info';
          } else {
            statusText = '未知';
            type = 'info';
            color = '#909399';
            statusClass = 'remark-unknown';
          }
          return {
            time: task.executionTime,
            content: task.taskName,
            type,
            color,
            user: task.createByStr || '',
            remark: statusText,
            statusClass
          };
        });
      } else {
        ElMessage.error(res.msg || '获取进度失败');
        timelineData.value = [];
        planStats.value = { totalDays: 0, executedDays: 0, totalTasks: 0, executedTasks: 0 };
      }
      timelineDialogVisible.value = true;
    })
    .catch(() => {
      ElMessage.error('获取进度失败');
      timelineData.value = [];
      planStats.value = { totalDays: 0, executedDays: 0, totalTasks: 0, executedTasks: 0 };
      timelineDialogVisible.value = true;
    });
}

// 初始化
onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped>
.sop-bulk-sending {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .create-info {
    font-size: 13px;
    color: #606266;
    line-height: 1.6;

    div {
      margin-bottom: 4px;
    }
  }

  .pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;

    .custom-pagination {
      :deep(.el-pagination__total) {
        margin-right: 16px;
      }

      :deep(.el-pagination__sizes) {
        margin-right: 16px;
      }
    }
  }
}

.task-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }

  .task-form {
    .el-form-item {
      margin-bottom: 22px;
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.detail-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100vh - 120px);
    overflow: hidden;
  }
}

:deep(.el-overlay) {
  .detail-dialog {
    --el-dialog-margin-top: 2vh !important;
  }
}

.timeline-stats {
  position: relative;
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 8px 0 0 0;
  background: transparent;
  border-radius: 0;
  box-shadow: none;
  flex-wrap: wrap;
  gap: 0 16px;
  .stat-group {
    display: flex;
    gap: 16px;
    align-items: center;
    position: relative;
  }
  .stat-group + .stat-group {
    position: relative;
    margin-left: 16px;
  }
  .stat-group + .stat-group::before {
    display: none;
  }
  .stat-item {
    background: none;
    border-radius: 0;
    padding: 0 8px;
    min-width: 60px;
    text-align: center;
    .stat-label {
      font-size: 12px;
      color: #888;
      margin-bottom: 1px;
    }
    .stat-value {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      .el-icon {
        background: none;
        border-radius: 0;
        color: #52c41a;
        font-size: 16px;
        padding: 0;
        box-shadow: none;
      }
    }
  }
  .highlight .stat-value {
    background: none;
    -webkit-background-clip: unset;
    -webkit-text-fill-color: unset;
    color: #52c41a;
  }
  .highlight .stat-label {
    color: #52c41a;
  }
  &::before {
    content: '';
    display: block;
    position: absolute;
    left: 50%;
    top: 8px;
    bottom: 8px;
    width: 1px;
    background: #f0f0f0;
    transform: translateX(-50%);
    border-radius: 1px;
    z-index: 1;
  }
}
@media (max-width: 700px) {
  .timeline-stats {
    flex-direction: column;
    gap: 8px 0;
    .stat-group + .stat-group {
      margin-left: 0;
      margin-top: 8px;
    }
    .stat-group + .stat-group::before {
      display: none;
    }
    &::before {
      display: none;
    }
  }
}

.timeline-wrapper {
  padding: 8px 0 0 0;
}
.timeline-card {
  background: #fafbfc;
  border-radius: 6px;
  padding: 10px 14px 8px 14px;
  box-shadow: none;
  margin-bottom: 4px;
  transition: none;
}
.timeline-title {
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 2px;
  color: #222;
}
.timeline-meta {
  color: #888;
  font-size: 12px;
  margin-top: 1px;
  display: flex;
  flex-direction: column;
  gap: 1px;
}
.timeline-remark {
  font-weight: 600;
}
.remark-info {
  color: #409eff;
}
.remark-success {
  color: #67c23a;
}
.remark-danger {
  color: #f56c6c;
}
.remark-warning {
  color: #e6a23c;
}
.remark-unknown {
  color: #909399;
}
:deep(.el-timeline-item__node) {
  box-shadow: none;
  background: #e6f7e6 !important;
  border: none !important;
}
:deep(.el-timeline-item__tail) {
  border-left: 2px solid #f0f0f0 !important;
}

.stat-unit {
  font-size: 13px;
  color: #888;
  font-weight: 400;
  margin-left: 2px;
}
</style>
